/**
 * AppDeviceService.java 
 * Copyright © 2009-2014, Liu Tao
 * 
 * @author Liu Tao
 * @create 2014年5月13日
 */
package com.pshare.appdevice.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.pshare.appdevice.bean.AppDevice;
import com.pshare.appdevice.mapper.AppDeviceMapper;
import com.pshare.constant.SeaxConstants;
import com.pshare.framework.exception.WrongParamException;
import com.pshare.framework.mapper.BaseMapper;
import com.pshare.framework.service.BaseService;

/**
 * 客户端设备信息服务层
 */
@Service
@Transactional
public class AppDeviceService extends BaseService<Long, AppDevice> {
	
	private static final Logger logger = Logger.getLogger(AppDeviceService.class);
	private static final Integer DEFAULT_OVERTIME_DAYS = 14;
	
	@Autowired
	private AppDeviceMapper appDeviceMapper;

	@Override
	protected BaseMapper<Long, AppDevice> getBaseMapper() {
		return appDeviceMapper;
	}
	
	/**
	 * 根据用户ID获取设备信息
	 * @param userId
	 * @param bizClientType 业务客户端类型
	 * @return List<Device>
	 */
	public List<AppDevice> getDevice(Long userId, Integer idClientType) {
		if (userId == null || userId < 1) {
			return new ArrayList<AppDevice>();
		}
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userId", userId);
		params.put("idClientType", idClientType);
		return query(params);
	}
	
	/**
	 * 根据用户ID列表获取设备信息
	 * @param userId
	 * @param bizClientType 业务客户端类型
	 * @return List<Device>
	 */
	public List<AppDevice> getDeviceByUserIds(List<Long> userIds, Integer idClientType) {
		if (userIds == null || userIds.size() == 0) {
			return new ArrayList<AppDevice>();
		}
		
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("userIds", userIds);
		params.put("idClientType", idClientType);
		return query(params);
	}
	
	/**
	 * 根据操作系统类型和业务端类型读取device列表
	 * @param osType 客户端操作系统类型
	 * @param idClientType 业务客户端类型
	 * @return List<Device>
	 */
	public List<AppDevice> getDeviceList(Integer osType, Integer idClientType) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("osType", osType);
		params.put("idClientType", idClientType);
		return query(params);
	}
	
	public AppDevice getDeviceByToken(String deviceToken) {
		return appDeviceMapper.getDeviceByToken(deviceToken);
	}
	
	
	public void updateUnread(Long id, String deviceToken, Integer unreadCount) {
		Map<String, Object> params = new HashMap<String, Object>();
		params.put("id", id);
		params.put("deviceToken", deviceToken);
		params.put("unreadCount", unreadCount);
		appDeviceMapper.updateUnread(params);
	}
	
	public void addUnreadCount(List<String> list, Integer count) {
		appDeviceMapper.addUnreadCount(list, count);
	}
	
	/** 
	 * 根据用户ID和设备deviceToken删除设备信息 
	 */
	public void delete(Long userId, String deviceToken) {
		if (userId == null && StringUtils.isBlank(deviceToken)) {
			logger.warn("userId is null and deviceToken is blank");
			throw new WrongParamException();
		}
		appDeviceMapper.delete(userId, deviceToken);
	}
	
	/**
	 * 根据设备deviceToken删除设备信息
	 * @param deviceToken
	 */
	public void removeDeviceToken(String deviceToken) {
		if (StringUtils.isBlank(deviceToken)) {
			return;
		}
		
		try {
			appDeviceMapper.delete(null, deviceToken);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	/**
	 * 清除过期的deviceToken
	 */
	public void clearOverTimeDeviceToken() {
		clearOverTimeDeviceToken(DEFAULT_OVERTIME_DAYS);
	}
	
	private void clearOverTimeDeviceToken(Integer days) {
		appDeviceMapper.clearOverTimeDeviceToken(days);
	}
	
	/**
	 * 更新设备信息
	 * @param device
	 */
	public void recordDeviceInfo(AppDevice appDevice) {
		if (appDevice == null) {
			logger.error("appDevice is null");
			return;
		}
		String token = appDevice.getDeviceToken();
		if (StringUtils.isBlank(token)) {
			logger.warn("device token is blank");
			return;
		}
		
		try {
			AppDevice old = getDeviceByToken(token);
			if (old != null) {
				old.setUserId(appDevice.getUserId());
				old.setOsType(appDevice.getOsType());
				old.setBizClientType(appDevice.getBizClientType());
				update(old);
			} else {
				add(appDevice);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
	}
	
	/**
	 * 更新未读条数
	 * @param deviceToken
	 * @param count 需要增减的条数
	 * @param action 1：增，-1：减
	 */
	public void updateUnreadCount(String deviceToken, Integer count, Integer action) {
		if(StringUtils.isBlank(deviceToken)) {
			logger.warn("deviceToken is blank");
			return;
		}
		AppDevice device = getDeviceByToken(deviceToken);
		if(device == null) {
			logger.warn("not exist devicetoken:" + deviceToken);
			return;
		}
		
		Integer newCount = null;
		Integer oldCount = device.getUnreadCount();
		if(action == SeaxConstants.ACTION_SUBSTRACT) {
			newCount = (oldCount - count) > 0 ? (oldCount - count) : 0;
		} else {
			newCount = oldCount + count;
		}
		updateUnread(device.getId(), null, newCount);
	}

	/**
	 * 清空未读条数
	 * @param deviceToken
	 */
	public void clearUnreadCount(String deviceToken) {
		if(StringUtils.isBlank(deviceToken)) {
			logger.warn("deviceToken is blank");
			return;
		}
		updateUnread(null, deviceToken, 0);
	}



	
}
